<template>
  <div class="create-post-container">
    <!-- 返回按钮 -->
    <div class="back-button-container">
      <button class="back-button" @click="goBackToList" title="返回帖子列表">
        <i class="fas fa-arrow-left"></i>
      </button>
    </div>
    
    <h1 class="page-title">发布新帖子</h1>

    <!-- 服务器错误提示 -->
    <div class="server-error" v-if="errors.server">
      <i class="fas fa-exclamation-circle"></i>
      <span>{{ errors.server }}</span>
    </div>

    <form class="post-form" @submit.prevent="handleSubmit">
      <!-- 帖子标题 -->
      <div class="form-group">
        <label for="title">标题 <span class="required">*</span></label>
        <input
            type="text"
            id="title"
            v-model="formData.postTitle"
            :class="{ 'error': errors.postTitle }"
            placeholder="请输入帖子标题"
            maxlength="100"
        >
        <div class="input-hint">
          <span class="char-count">{{ formData.postTitle.length }}/100</span>
          <p class="error-message" v-if="errors.postTitle">{{ errors.postTitle }}</p>
        </div>
      </div>

      <!-- 帖子内容 -->
      <div class="form-group">
        <label for="content">内容 <span class="required">*</span></label>
        <textarea
            id="content"
            v-model="formData.postContent"
            :class="{ 'error': errors.postContent }"
            rows="15"
            placeholder="请输入帖子内容，详细描述可以获得更多关注..."
            maxlength="10000"
        ></textarea>
        <div class="input-hint">
          <span class="char-count">{{ formData.postContent.length }}/10000 字符</span>
          <p class="error-message" v-if="errors.postContent">{{ errors.postContent }}</p>
        </div>
      </div>

      <!-- 帖子分类 -->
      <div class="form-group">
        <label for="category">分类 <span class="required">*</span></label>
        <select
            id="category"
            v-model="formData.categoryName"
            :class="{ 'error': errors.categoryName }"
        >
          <option value="">请选择分类</option>
          <option value="技术讨论">技术讨论</option>
          <option value="经验分享">经验分享</option>
          <option value="问题求助">问题求助</option>
          <option value="其他">其他</option>
        </select>
        <p class="error-message" v-if="errors.categoryName">{{ errors.categoryName }}</p>
      </div>

      <!-- 帖子状态 -->
      <div class="form-group">
        <label for="status">状态 <span class="required">*</span></label>
        <select
            id="status"
            v-model="formData.status"
            :class="{ 'error': errors.status }"
        >
          <option :value="1">发布</option>
          <option :value="0">草稿</option>
        </select>
        <p class="error-message" v-if="errors.status">{{ errors.status }}</p>
      </div>

      <!-- 封面图片 -->
      <div class="form-group">
        <label for="cover_Image">封面图片 <span class="required">*</span></label>
        <input
            type="file"
            id="cover_Image"
            accept="image/*"
            @change="handleImageUpload"
        >
        <p class="error-message" v-if="errors.coverImage">{{ errors.coverImage }}</p>
        <div class="image-preview" v-if="imagePreviewUrl">
          <img :src="imagePreviewUrl" alt="封面预览">
          <button type="button" class="remove-image" @click="clearImage">×</button>
        </div>
        <div class="upload-hint" v-if="!imagePreviewUrl">
          <small>支持jpg、png、gif格式，文件大小不超过5MB。图片将高度压缩优化，建议使用简单图像（如纯色背景、简单形状等）</small>
        </div>
      </div>

      <!-- 提交按钮 -->
      <div class="form-actions">
        <button
            type="submit"
            class="submit-btn"
            :disabled="isSubmitting"
        >
          <span v-if="!isSubmitting">
            {{ formData.status === 1 ? '发布帖子' : '保存草稿' }}
          </span>
          <span v-if="isSubmitting">
            <i class="fas fa-spinner fa-spin"></i> 处理中...
          </span>
        </button>
        <button
            type="button"
            class="cancel-btn"
            @click="handleCancel"
            :disabled="isSubmitting"
        >
          取消
        </button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'; // 假设使用Element Plus的消息提示
import { invitationAPI } from '../services/api';

// 表单数据
const formData = ref({
  postTitle: '',      // 对应后端 postTitle
  postContent: '',    // 对应后端 postContent
  categoryName: '',   // 对应后端 categoryName
  coverImage: '',     // 对应后端 coverImage
  status: 1          // 对应后端 status (1:已发布)
});

// 错误信息
const errors = reactive({
  postTitle: '',
  postContent: '',
  categoryName: '',
  status: '',
  coverImage: '',
  server: ''
});

// 状态管理
const imagePreviewUrl = ref(''); // 预览用Base64
const isSubmitting = ref(false);
const router = useRouter();
const isDirty = ref(false);

// 返回帖子列表
const goBackToList = () => {
  if (isDirty.value) {
    if (confirm('确定要返回吗？已输入的内容将会丢失。')) {
      router.push('/invitations');
    }
  } else {
    router.push('/invitations');
  }
};
// 监听表单变化，标记为已修改
watch([
  () => formData.value.postTitle,
  () => formData.value.postContent,
  () => formData.value.categoryName,
  () => formData.value.coverImage,
  () => formData.value.status
], () => {
  isDirty.value = true;
});

/**
 * 超级图片压缩，适应数据库字段限制
 */
const superCompressImage = async (file) => {
  return new Promise((resolve) => {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const img = new Image();
    
    img.onload = () => {
      // 极小尺寸以适应数据库
      let width = 150;
      let height = 100;
      
      // 按比例计算尺寸
      const ratio = Math.min(width / img.width, height / img.height);
      width = Math.floor(img.width * ratio);
      height = Math.floor(img.height * ratio);
      
      canvas.width = width;
      canvas.height = height;
      
      // 绘制并压缩
      ctx.drawImage(img, 0, 0, width, height);
      
      // 极限压缩质量
      let compressed = canvas.toDataURL('image/jpeg', 0.1);
      
      // 如果还是过大，再次缩小
      if (compressed.length > 5000) {
        canvas.width = Math.max(width * 0.6, 80);
        canvas.height = Math.max(height * 0.6, 60);
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        compressed = canvas.toDataURL('image/jpeg', 0.05);
      }
      
      console.log('超级压缩结果:', {
        原始文件: file.size + ' bytes',
        压缩后: compressed.length + ' chars',
        尺寸: canvas.width + 'x' + canvas.height,
        压缩比: ((1 - compressed.length / file.size) * 100).toFixed(1) + '%'
      });
      
      resolve(compressed);
    };
    
    img.src = URL.createObjectURL(file);
  });
};

/**
 * 图片上传处理 - Base64编码上传
 */
const handleImageUpload = async (e) => {
  const file = e.target.files?.[0];
  if (!file) return;
  
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    errors.coverImage = '请选择图片文件';
    return;
  }
  
  // 验证文件大小 (5MB)
  if (file.size > 5 * 1024 * 1024) {
    errors.coverImage = '图片大小不能超过5MB';
    return;
  }
  
  try {
    // 使用超级压缩
    const compressedBase64 = await superCompressImage(file);
    
    // 检查最终大小
    if (compressedBase64.length > 5000) {
      errors.coverImage = '图片太复杂，请选择更简单的图像（纯色背景、简单形状等）';
      return;
    }
    
    // 保存Base64字符串
    formData.value.coverImage = compressedBase64;
    imagePreviewUrl.value = compressedBase64;
    
    // 清除错误信息
    errors.coverImage = '';
    
    console.log('图片上传成功！最终大小:', compressedBase64.length, '字符');
    
  } catch (error) {
    console.error('图片处理失败:', error);
    errors.coverImage = '图片处理失败，请重试';
  }
};

// 移除图片
const clearImage = () => {
  formData.value.coverImage = '';
  imagePreviewUrl.value = '';
  document.getElementById('cover_Image').value = '';
  errors.coverImage = '';
};

// 表单验证
const validateForm = () => {
  let isValid = true;
  // 清空所有错误
  Object.keys(errors).forEach(key => errors[key] = '');

  // 验证标题 (对应@NotBlank和@Length验证)
  if (!formData.value.postTitle.trim()) {
    errors.postTitle = '帖子标题不可为空';
    isValid = false;
  } else if (formData.value.postTitle.length > 100) {
    errors.postTitle = '标题不能超过100字符';
    isValid = false;
  }

  // 验证内容 (对应@NotBlank验证)
  if (!formData.value.postContent.trim()) {
    errors.postContent = '帖子内容不可为空';
    isValid = false;
  } else if (formData.value.postContent.length > 10000) {
    errors.postContent = '帖子内容不能超过10000字符';
    isValid = false;
  }

  // 验证分类 (对应@NotBlank验证)
  if (!formData.value.categoryName) {
    errors.categoryName = '分类名不可空';
    isValid = false;
  }

  // 验证封面图片 (对应@NotBlank验证)
  if (!formData.value.coverImage) {
    errors.coverImage = '封面图片不可为空';
    isValid = false;
  }

  // 验证状态
  if (formData.value.status !== 0 && formData.value.status !== 1) {
    errors.status = '请选择正确的状态';
    isValid = false;
  }

  return isValid;
};

// 提交表单
const handleSubmit = async () => {
  // 检查用户登录状态
  const isLoggedIn = localStorage.getItem('isLogin') === 'true';
  if (!isLoggedIn) {
    ElMessage.error('请先登录后再发布帖子');
    router.push('/login');
    return;
  }

  if (!validateForm()) {
    return; // 验证失败时阻止提交
  }

  try {
    isSubmitting.value = true;
    
    // 构建符合后端接口的JSON数据
    const invitationData = {
      postTitle: formData.value.postTitle,
      postContent: formData.value.postContent,
      categoryName: formData.value.categoryName,
      coverImage: formData.value.coverImage, // Base64字符串
      status: formData.value.status
      // 用户信息通过Session获取
    };
    
    console.log('发送JSON数据，图片大小:', formData.value.coverImage?.length, '字符');
    
    await invitationAPI.createInvitation(invitationData);
    
    ElMessage.success('帖子创建成功！');
    isDirty.value = false;
    router.push('/products');
  } catch (error) {
    console.error('创建失败:', error);
    
    // 处理后端验证错误
    if (error.message.includes('USER_NOT_LOGIN') || 
        error.message.includes('登录') || 
        error.message.includes('未登录')) {
      ElMessage.error('登录状态已失效，请重新登录');
      localStorage.removeItem('isLogin');
      localStorage.removeItem('userInfo');
      router.push('/login');
    } else if (error.message.includes('Data too long for column')) {
      // 处理数据库字段过长错误
      if (error.message.includes('post_content')) {
        errors.postContent = '帖子内容过长，请缩短内容后重试';
      } else if (error.message.includes('cover_image')) {
        errors.coverImage = '图片数据过大，请选择更小的图片';
      } else if (error.message.includes('post_title')) {
        errors.postTitle = '帖子标题过长，请缩短后重试';
      } else {
        errors.server = '数据过长，请检查输入内容';
      }
    } else {
      errors.server = error.message || '网络错误，请稍后重试';
    }
  } finally {
    isSubmitting.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  if (!isDirty.value) {
    router.back();
    return;
  }

  if (confirm(`确定要取消${formData.value.status === 1 ? '发布' : '保存'}吗？已输入的内容将会丢失。`)) {
    router.back();
  }
};

// 监听页面刷新或关闭事件
window.addEventListener('beforeunload', (e) => {
  if (isDirty.value && !isSubmitting.value) {
    e.preventDefault();
    e.returnValue = '您有未保存的内容，确定要离开吗？';
    return e.returnValue;
  }
});
</script>

<style scoped>
.create-post-container {
  max-width: none; /* 移除最大宽度限制 */
  width: 100%; /* 占满屏幕宽度 */
  margin: 0;
  padding: 20px;
  padding-left: 280px; /* 为侧边栏留出空间 */
  padding-right: 40px; /* 右侧也留出一些空间 */
  min-height: 100vh; /* 占满屏幕高度 */
  box-sizing: border-box;
}

/* 返回按钮 */
.back-button-container {
  margin-bottom: 20px;
}

.back-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(66, 185, 131, 0.3);
  transition: all 0.3s ease;
  font-size: 16px;
}

.back-button:hover {
  background: #369870;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(66, 185, 131, 0.4);
}

.back-button:active {
  transform: translateY(0);
}

.page-title {
  color: #333;
  border-bottom: 2px solid #42b983;
  padding-bottom: 10px;
  margin-bottom: 30px;
}

.server-error {
  background-color: #fff1f0;
  border: 1px solid #ffa39e;
  border-radius: 4px;
  padding: 12px 16px;
  margin-bottom: 20px;
  color: #f5222d;
  display: flex;
  align-items: center;
}

.server-error i {
  margin-right: 8px;
  font-size: 18px;
}

.post-form {
  background-color: #fff;
  padding: 40px; /* 增加内边距 */
  border-radius: 12px; /* 增大圆角 */
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1); /* 增强阴影效果 */
  max-width: none; /* 移除宽度限制 */
  width: 100%; /* 占满容器 */
}

.form-group {
  margin-bottom: 35px; /* 增大表单组件间距 */
}

label {
  display: block;
  margin-bottom: 10px; /* 增大标签与输入框间距 */
  color: #555;
  font-weight: 500;
  font-size: 16px; /* 增大标签字体 */
}

.required {
  color: #ff4d4f;
}

input, textarea, select {
  width: 100%;
  padding: 15px; /* 增大内边距 */
  border: 1px solid #ddd;
  border-radius: 6px; /* 增大圆角 */
  font-size: 16px;
  transition: border-color 0.2s;
  line-height: 1.5; /* 增大行高 */
}

input:focus, textarea:focus, select:focus {
  border-color: #42b983;
  outline: none;
  box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.2);
}

textarea {
  resize: vertical;
}

.error {
  border-color: #ff4d4f !important;
}

.error:focus {
  box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2);
}

.error-message {
  color: #ff4d4f;
  font-size: 14px;
  margin-top: 5px;
  min-height: 20px;
}

.input-hint {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.char-count {
  font-size: 14px;
  color: #888;
}

/* 图片上传区域 */
.image-upload-area {
  display: inline-block;
}

.file-input {
  display: none;
}

.upload-label {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 12px 20px;
  background-color: #f5f5f5;
  border: 1px dashed #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  color: #666;
}

.upload-label:hover {
  background-color: #eee;
  border-color: #42b983;
  color: #42b983;
}

.upload-label i {
  margin-right: 8px;
}

.image-preview {
  margin-top: 15px;
  position: relative;
  display: inline-block;
}

.image-preview img {
  max-width: 500px; /* 增大图片预览尺寸 */
  max-height: 350px;
  border-radius: 8px; /* 增大圆角 */
  border: 2px solid #ddd; /* 增强边框 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); /* 增强阴影 */
}

.remove-image {
  position: absolute;
  top: -10px;
  right: -10px;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background-color: #ff4d4f;
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  padding: 0;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  transition: background-color 0.2s;
}

.remove-image:hover {
  background-color: #f5222d;
}

.image-info {
  margin-top: 8px;
  font-size: 14px;
  color: #666;
}

.upload-hint {
  margin-top: 8px;
}

.upload-hint small {
  color: #888;
  font-size: 12px;
}

/* 按钮区域 */
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20px; /* 增大按钮间距 */
  margin-top: 50px; /* 增大顶部边距 */
  padding-top: 30px; /* 增加上边距 */
  border-top: 1px solid #f0f0f0; /* 添加分割线 */
}

.submit-btn {
  background-color: #42b983;
  color: white;
  border: none;
  padding: 15px 30px; /* 增大按钮尺寸 */
  border-radius: 6px; /* 增大圆角 */
  cursor: pointer;
  font-size: 16px;
  font-weight: 500; /* 增强字体 */
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease; /* 增强过渡效果 */
  min-width: 120px; /* 设置最小宽度 */
}

.submit-btn:hover {
  background-color: #369870;
  transform: translateY(-2px); /* 添加悬停效果 */
  box-shadow: 0 4px 12px rgba(66, 185, 131, 0.3);
}

.submit-btn i {
  margin-right: 8px;
}

.submit-btn:disabled {
  background-color: #a5d6a7;
  cursor: not-allowed;
}

.cancel-btn {
  background-color: transparent;
  color: #666;
  border: 2px solid #ddd; /* 增强边框 */
  padding: 13px 30px; /* 调整内边距以匹配边框 */
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 120px;
}

.cancel-btn:hover {
  background-color: #f5f5f5;
  border-color: #ccc;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.cancel-btn:disabled {
  color: #ccc;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .create-post-container {
    padding-right: 20px; /* 中等屏幕减少右边距 */
  }
}

@media (max-width: 768px) {
  .create-post-container {
    padding: 15px;
    padding-left: 15px; /* 移动端减少左边距 */
    padding-right: 15px;
  }
  
  .post-form {
    padding: 25px; /* 移动端减少内边距 */
  }
  
  .form-actions {
    flex-direction: column;
    gap: 15px;
  }
  
  .submit-btn, 
  .cancel-btn {
    width: 100%;
    min-width: auto;
  }
  
  .image-preview img {
    max-width: 100%; /* 移动端图片占满宽度 */
    max-height: 250px;
  }
  
  textarea {
    rows: 12; /* 移动端减少文本区域高度 */
  }
}
</style>
